package com.pandora.credit.service.impl;

import com.pandora.common.util.*;
import com.pandora.credit.dao.TerminalDao;
import com.pandora.credit.dto.request.TerminalInfoRequest;
import com.pandora.credit.entity.Customer;
import com.pandora.credit.entity.Terminal;
import com.pandora.credit.exception.EmptyRequestException;
import com.pandora.credit.exception.terminal.EmptyTerminalIdException;
import com.pandora.credit.service.CustomerService;
import com.pandora.credit.service.TerminalService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author developer
 */
@Service
public class TerminalServiceImpl implements TerminalService {
    Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private TerminalDao terminalDao;

    @Autowired
    private CustomerService customerService;

    @Override
    public Terminal getByUniqueNoFirst(String uniqueNo, long userId) {
        List<Terminal> list = terminalDao.queryByUniqueNo(uniqueNo, userId);
        if(list != null && list.size() > 0){
            return list.get(0);
        }
        return null;
    }

    @Override
    public void update(Terminal terminal) {
        terminalDao.update(terminal);
    }

    @Override
    public void insert(Terminal terminal) {
        terminalDao.insert(terminal);
    }

    @Override
    public void uploadTerminalInfo(TerminalInfoRequest terminalInfoRequest, String accessToken, String authorizationToken) {
        logger.info("uploadTerminalInfo come in");
        if (terminalInfoRequest == null) {
            logger.info("Empty request for POSTing terminal!");
            throw new EmptyRequestException();
        }
        String custId = null;
        String terminalId = terminalInfoRequest.getTerminalId();
        if (VerifyUtil.isEmpty(terminalId)) {
            logger.info("Empty request for POSTing terminal!");
            throw new EmptyTerminalIdException();
        }
        if (!VerifyUtil.isEmpty(authorizationToken)) {
            String mobile = JedisUtil.get(Constants.BUSINESS_REDIS_URL,
                    StringUtils.getStrParam(Constants.AUTHORIZATION_TOKEN_KEY, authorizationToken));
            Customer cus = customerService.getByMobile(mobile);
            if (cus != null) {
                custId = String.valueOf(cus.getId());
            }
        }
        logger.info("cusId[{}]", custId);
        if (!VerifyUtil.isEmpty(accessToken)) {
            JedisUtil.set(Constants.BUSINESS_REDIS_URL,
                    StringUtils.getStrParam(Constants.TERMINAL_ACCESS_TOKEN_KEY, terminalId),
                    accessToken,
                    Constants.TERMINAL_TOKEN_EXPIRATION);
            JedisUtil.set(Constants.BUSINESS_REDIS_URL,
                    StringUtils.getStrParam(Constants.ACCESS_TOKEN_TERMINAL_KEY, accessToken),
                    terminalId,
                    Constants.TERMINAL_TOKEN_EXPIRATION);
        }
        Terminal terminal;
        String pushToken = terminalInfoRequest.getPushToken();
        String deviceModel = terminalInfoRequest.getDeviceModel();
        String osVersion = terminalInfoRequest.getOsVersion();
        String factoryOsVersion = terminalInfoRequest.getFactoryOsVersion();
        String bundleVersion = terminalInfoRequest.getBundleVersion();
        if (terminalId.equals(Constants.HTML_TERMINAL)) {
            logger.info("terminalId.equals(Constants.HTML_TERMINAL)");
            if (!VerifyUtil.isEmpty(custId)) {
                logger.info("!VerifyUtil.isEmpty(custId)");
                terminal = getByUniqueNoFirst(terminalId, Integer.parseInt(custId));
            } else {
                return;
            }
        } else {
            terminal = getByUniqueNoFirst(terminalId, -1);
        }
        logger.info("terminal[{}]", terminal);
        if(terminal == null) {
            terminal = new Terminal();
            terminal.setId(System.currentTimeMillis() * 1000);
            terminal.setUniqueNo(terminalId);
            terminal.setPushToken(pushToken);
            terminal.setDeviceModel(deviceModel);
            terminal.setOsVersion(osVersion);
            terminal.setFactoryOsVersion(factoryOsVersion);
            terminal.setBundleVersion(bundleVersion);
            terminal.setStatus(Constants.STATUS_ENABLED);
            if(!StringUtils.isEmpty(custId)) {
                terminal.setUserId(Long.parseLong(custId));
            }
            terminal.setCreateTime(DateUtil.getNowTimestamp());
            terminal.setUpdateTime(DateUtil.getNowTimestamp());
            insert(terminal);
        } else {
            if(!StringUtils.isEmpty(custId)) {
                terminal.setUserId(Long.parseLong(custId));
            }
            terminal.setPushToken(pushToken);
            terminal.setDeviceModel(deviceModel);
            terminal.setOsVersion(osVersion);
            terminal.setFactoryOsVersion(factoryOsVersion);
            terminal.setBundleVersion(bundleVersion);
            terminal.setStatus(Constants.STATUS_ENABLED);
            terminal.setUpdateTime(DateUtil.getNowTimestamp());
            update(terminal);
        }
        logger.info("terminal end");
    }
}
